/*
 * $Id: $
 */
package org.rcgwt.client.ui.grid.internal;

import org.rcgwt.client.ui.grid.internal.model.IElementModel;

/**
 * 
 * @author Olivier Oeuillot (latest modification by $Author: $)
 * @version $Revision: $ $Date: $
 */
public class DefaultModelElementDelta<T extends IElementModel> extends
        AbstractModelElementDelta<T> {

    private static final int CONTENT_CHANGED = 0x0001;

    private static final int STATE_MASK_CHANGED = 0x0002;

    private int kind;

    private int bits;

    private int oldStateMask;

    private int mask;

    private int newStateMask;

    protected DefaultModelElementDelta(T elementModel) {
        super(elementModel);
    }

    protected void updateKind(int kindMask) {
        this.kind |= kindMask;
    }

    @Override
    public int getBits() {
        return bits;
    }

    @Override
    public int getKind() {
        return kind;
    }

    @Override
    public int getMask() {
        return mask;
    }

    @Override
    public int getOldStateMask() {
        return oldStateMask;
    }

    @Override
    public boolean hasContentChanged() {
        return (kind & CONTENT_CHANGED) > 0;
    }

    @Override
    public boolean hasStateMaskChanged() {
        return (kind & STATE_MASK_CHANGED) > 0;
    }

    @Override
    public void performContentChanged() {
        kind |= CONTENT_CHANGED;
    }

    @Override
    public void performStateMaskChanged(int oldStateMask, int newStateMask,
            int mask, int bits) {
        if (hasStateMaskChanged()) {
            if (this.oldStateMask == newStateMask) {
                kind &= ~STATE_MASK_CHANGED;
                return;
            }

            this.bits |= bits;
            this.mask &= mask;
            this.newStateMask = newStateMask;
            return;
        }

        updateKind(STATE_MASK_CHANGED);
        this.oldStateMask = oldStateMask;
        this.newStateMask = newStateMask;
        this.mask = mask;
        this.bits = bits;

    }

    @Override
    public String toString() {
        return "[DefaultModelElementDelta model=" + getModelElement().getType()
                + " " + toValuesString() + "]";
    }

    protected String toValuesString() {
        return "kind=0x" + Integer.toHexString(kind) + " bits=0x"
                + Integer.toHexString(bits) + " mask=0x"
                + Integer.toHexString(mask) + " oldState=0x"
                + Integer.toHexString(oldStateMask);
    }
}